package com.fsp.blog.admin.service;

import com.fsp.blog.admin.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author fushengping
 * @className SecurityUserService
 * @description 登录认证
 * @date 2021/11/24 21:37
 */
@Component
public class SecurityUserService implements UserDetailsService {
    @Autowired
    private AdminService adminService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*
        * 1.当用户登录的时候，springSecurity 就会将请求 转发到此，请求含有用户信息
        * 2.根据用户名 查找用户，不存在 抛出异常，认证失败;
        * 3.存在 将用户名，密码，授权列表 组装成springSecurity的User对象 并返回
        * */
        Admin admin = adminService.findAdminByUserName(username);
        if (admin == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //存在，组装成springSecurity的User对象 并返回
        UserDetails userDetails = new User(username,admin.getPassword(),new ArrayList<>());//不在这做认证授权，列表为空
        return userDetails;
    }
}
